import axios from 'axios';

// 根据环境设置API基础URL
const isDev = window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1';
const API_BASE_URL = isDev
  ? '/api'  // 开发环境使用相对路径，通过Vite代理
  : 'https://ghiblioart.wwh-ai-sites.xin/api';  // 生产环境使用完整URL

// 创建axios实例
const apiClient = axios.create({
  baseURL: API_BASE_URL,
  headers: {
    'Content-Type': 'application/json',
    'accept': 'application/json'
  }
});

// 设置token的函数，可以从组件中调用
export const setAuthToken = (token: string) => {
  if (token) {
    apiClient.defaults.headers.common['Authorization'] = `Bearer ${token}`;
  } else {
    delete apiClient.defaults.headers.common['Authorization'];
  }
};

// 图像生成接口
export interface ImageGenerationParams {
  model: string;
  prompt: string;
  n: number;
  size: string;
}

export interface ImageGenerationResult {
  success: boolean;
  result: {
    created: number;
    data: Array<{
      revised_prompt: string;
      url: string;
    }>;
  };
}

// 图像生成API
export const generateImage = async (params: ImageGenerationParams): Promise<ImageGenerationResult> => {
  try {
    const response = await apiClient.post<ImageGenerationResult>('/images/generations', params);
    return response.data;
  } catch (error) {
    console.error('Image generation error:', error);
    throw error;
  }
};

export default {
  generateImage,
  setAuthToken
};
